package reading.util.utils;

import reading.util.aes.BCConvert;
import reading.util.aes.WordNode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 创建时间：2016年8月30日 下午3:01:12
 *
 * 思路： 创建一个FilterSet，枚举了0~65535的所有char是否是某个敏感词开头的状态
 *
 * 判断是否是 敏感词开头 | | 是 不是 获取头节点 OK--下一个字 然后逐级遍历，DFA算法
 *
 * @author andy
 * @version 2.2
 */
public class WordFilter {

    /**存储首字*/
    private static final FilterSet set = new FilterSet();
    /**存储节点*/
    private static final Map<Integer, WordNode> nodes = new HashMap<>(1024, 1);
    /**敏感词过滤替换*/
    private static final char SIGN = '*';

    static {
        try {
            init();
        } catch (Exception e) {
            throw new RuntimeException("初始化过滤器失败");
        }
    }

    private static void init() {
        // 获取敏感词
        addSensitiveWord();
    }

    /**
     * 增加敏感词
     * @param path
     * @return
     */
    private static List<String> readWordFromFile(String path) {
        List<String> words;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(WordFilter.class.getClassLoader().getResourceAsStream(path)));
            words = new ArrayList<String>(1200);
            for (String buf = ""; (buf = br.readLine()) != null;) {
                if (buf == null || buf.trim().equals("")) {
                    continue;
                }
                words.add(buf);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
            }
        }
        return words;
    }



    /**
     * 添加DFA节点
     *
     */
    private static void addSensitiveWord() {
         List<String> words=new ArrayList<>();
        words.add("逗比");
        words.add("fuck");
        words.add("@");
        words.add("哇哈哈哈");
        if (words != null && words.size() > 0) {
            char[] chs;
            int fchar;
            int lastIndex;
            WordNode fnode;
            for (String curr : words) {
                chs = curr.toCharArray();
                fchar = charConvert(chs[0]);
                if (!set.contains(fchar)) {
                    set.add(fchar);
                    fnode = new WordNode(fchar, chs.length == 1);
                    nodes.put(fchar, fnode);
                } else {
                    fnode = nodes.get(fchar);
                    if (!fnode.isLast() && chs.length == 1) {
                        fnode.setLast(true);
                    }
                }
                lastIndex = chs.length - 1;
                for (int i = 1; i < chs.length; i++) {
                    fnode = fnode.addIfNoExist(charConvert(chs[i]), i == lastIndex);
                }
            }
        }
    }

    /**
     * 过滤判断 将敏感词转化为成屏蔽词
     * @param src
     * @return
     */
    public static final String doFilter(final String src) {
        char[] chs = src.toCharArray();
        int length = chs.length;
        int currc;
        int k;
        WordNode node;
        StringBuilder stringBuilder= new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append(chs[i]);
            currc = charConvert(chs[i]);
            if (!set.contains(currc)) {
                continue;
            }
            node = nodes.get(currc);
            if (node == null) {
                continue;
            }
            boolean couldMark = false;
            int markNum = -1;
            if (node.isLast()) {
                couldMark = true;
                markNum = 0;
            }
            k = i;
            for (; ++k < length;) {
                int temp = charConvert(chs[k]);
                node = node.querySub(temp);
                if (node == null) {
                    break;
                }
                if (node.isLast()) {
                    couldMark = true;
                    markNum = k - i;
                }
            }
            if (couldMark) {
                StringBuilder span= new StringBuilder("<span style=\"color:red\">");
                for (k = 0; k <= markNum; k++) {
                    span.append(chs[k + i]);
                }
                stringBuilder=new StringBuilder(stringBuilder.substring(0,stringBuilder.length()-1));
                stringBuilder.append(span.append("</span>"));
                i = i + markNum;
            }

        }
        return stringBuilder.toString();
    }



    /**
     * 大写转化为小写 全角转化为半角
     *
     * @param src
     * @return
     */
    private static int charConvert(char src) {
        int r = BCConvert.qj2bj(src);
        return (r >= 'A' && r <= 'Z') ? r + 32 : r;
    }

}